import config from '@/utils/config.js';

const Base_Url = config.API_BASE_URL;

export const request = (config = {}) => {
	let { url, method='GET', header = {}, data, showLoading = false } = config;
	header['Authorization'] = `Bearer ${uni.getStorageSync("accessToken")}`;
	
	if (showLoading) {
		uni.showLoading({
			title: '加载中'
		})
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${Base_Url}${url}`,
			header,
			method,
			data,
		}).then((res) => {
			if (res.statusCode == 200) {
				resolve(res.data)
			} else if (res.statusCode == 401) {
				console.log('Token Expired');
			}
		}).catch((err) => {
			reject(err);
		}).finally(() => {
			if (showLoading) {
				uni.hideLoading();
			}
		})
	})
}

export const upload = (config = {}) => {
	let { url, header = {}, data } = config;
	let { filePath, name, fileType } = data;
	header['Authorization'] = `Bearer ${uni.getStorageSync("accessToken")}`;
	header['Content-Type'] = 'multipart/form-data;charset=UTF-8';
	uni.showLoading({title: '加载中'});
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${Base_Url}${url}`,
			header,
			filePath,
			name,
			fileType,
		}).then((res) => {
			if (res.statusCode == 200) {
				resolve(JSON.parse(res.data));
			} else if (res.statusCode == 401) {
				console.log('Token Expired');
			}
		}).catch((err) => {
			reject(err)
		}).finally(() => {
			uni.hideLoading()
		})
	});
}